package iot;

import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;

import com.yang.serialport.utils.ByteUtils;
import com.yang.serialport.utils.ShowUtils;

import gnu.io.PortInUseException;
import gnu.io.SerialPort;

import iot.serialthread;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import com.aliyun.iot.demo.Test;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTextField;
import javax.swing.text.DefaultCaret;

/**
 * 主界面
 *
 * @author yangle
 */
@SuppressWarnings("all")
public class MainFrame extends JFrame {

    // 程序界面宽度
    public final int WIDTH = 630;
    // 程序界面高度
    public final int HEIGHT = 590;

    // 数据显示区
    public static JTextArea mDataView = new JTextArea();
    private JScrollPane mScrollDataView = new JScrollPane(mDataView);

    //字符串打印区
    private JTextField mDataViewID_1 = new JTextField();
    private JTextField mDataViewID_2 = new JTextField();
    private JTextField mDataViewID_3 = new JTextField();
    private JScrollPane mScrollDataViewID = new JScrollPane();
    private JButton mButtonID = new JButton("打印上面的数据");

    //显示设备列表
    private JScrollPane mDriver = new JScrollPane();
    private JButton mButtonDriver = new JButton("显示设备列表");
    
    // 串口设置面板
    private JPanel mSerialPortPanel = new JPanel();
    private JLabel mSerialPortLabel1 = new JLabel("上网卡串口");
    private JLabel mSerialPortLabel2 = new JLabel("打印机串口");
    private JLabel mBaudrateLabel = new JLabel("波特率");
    private JComboBox mCommChoice1 = new JComboBox();
    private JComboBox mCommChoice2 = new JComboBox();
    private JComboBox mBaudrateChoice = new JComboBox();
    private ButtonGroup mDataChoice = new ButtonGroup();
    private static JRadioButton mDataHexChoice = new JRadioButton("Hex", true);
    private static JRadioButton mDataASCIIChoice = new JRadioButton("ASCII");
    private static JRadioButton mDataIDSameChoice = new JRadioButton("同一个ID不打印", true);
    private static JRadioButton mDataAliyunChoice = new JRadioButton("注册到阿里云", true);

    // 操作面板
    private JPanel mOperatePanel = new JPanel();
    private JTextArea mDataInput = new JTextArea();
    public static JButton mSerialPortOperate = new JButton("打开串口");
    private JButton mSendData = new JButton("发送数据");

    // 串口列表
    private List<String> mCommList = null;
    // 串口对象
    public static SerialPort mSerialport;   //上网卡串口
    public static SerialPort mSerialport2;        //打印机串口
    private static String strLast = "";                    //保留上次的ID
    private static Vector<String> vector = new Vector();   //存储的需要发送到打印机的数据
    private static String strProductKeyString = "a1ifTDLmxkm";        //设备Key
    public static String serialPortAliyunString = null;//保存的阿里云打开时的串口
    public static int ID_ISOK = 0;

    public MainFrame() {
        initView();
        initComponents();
        actionListener();
        initData();
    }

    /**
     * 初始化窗口
     */
    private void initView() {
        // 关闭程序
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        // 禁止窗口最大化
        setResizable(true);

        // 设置程序窗口居中显示
        Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setBounds(p.x - WIDTH / 2, p.y - HEIGHT / 2, WIDTH, HEIGHT);
        this.setLayout(null);

//        mDataView.setCaretPosition(mDataView.getText().length());//滚动条显示始终显示最下面
        DefaultCaret caret = (DefaultCaret) mDataView.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        setTitle("串口通信");
    }

    /**
     * 初始化控件
     */
    private void initComponents() {
        //设备列表
        mButtonDriver.setBounds(16, 30, 130, 30);
        mDriver.add(mButtonDriver);
        mDriver.setBorder(BorderFactory.createTitledBorder("设备列表"));
        mDriver.setBounds(10, 360, 200, 130);
        mDriver.setLayout(null);
        add(mDriver);
        
        //要打印的字符串
        mDataViewID_1.setBounds(16, 20, 150, 30);
        mDataViewID_2.setBounds(16, 50, 150, 30);
        mDataViewID_3.setBounds(16, 80, 150, 30);
        mDataViewID_1.setFocusable(true);
        mScrollDataViewID.setBounds(416, 10, 200, 200);
        mScrollDataViewID.setBorder(BorderFactory.createTitledBorder("要打印的字符串"));
        mButtonID.setFocusable(false);
        mButtonID.setBounds(16, 150, 130, 30);
        mScrollDataViewID.add(mDataViewID_1);
        mScrollDataViewID.add(mDataViewID_2);
        mScrollDataViewID.add(mDataViewID_3);
        mScrollDataViewID.add(mButtonID);
        mScrollDataViewID.setLayout(null);
        add(mScrollDataViewID);
        //add(mButtonID);

        // 数据显示
        mDataView.setFocusable(true);
        mScrollDataView.setBounds(10, 10, 405, 200);
        add(mScrollDataView);

        // 串口设置
        mSerialPortPanel.setBorder(BorderFactory.createTitledBorder("串口设置"));
        mSerialPortPanel.setBounds(10, 220, 200, 130);
        mSerialPortPanel.setLayout(null);
        add(mSerialPortPanel);

        mSerialPortLabel1.setForeground(Color.gray);
        mSerialPortLabel1.setBounds(10, 25, 80, 20);
        mSerialPortPanel.add(mSerialPortLabel1);

        mSerialPortLabel2.setForeground(Color.gray);
        mSerialPortLabel2.setBounds(10, 60, 80, 20);
        mSerialPortPanel.add(mSerialPortLabel2);

        mCommChoice1.setFocusable(false);
        mCommChoice1.setBounds(80, 25, 100, 20);
        mSerialPortPanel.add(mCommChoice1);

        mCommChoice2.setFocusable(false);
        mCommChoice2.setBounds(80, 60, 100, 20);
        mSerialPortPanel.add(mCommChoice2);

        mBaudrateLabel.setForeground(Color.gray);
        mBaudrateLabel.setBounds(10, 95, 40, 20);
        mSerialPortPanel.add(mBaudrateLabel);

        mBaudrateChoice.setFocusable(false);
        mBaudrateChoice.setBounds(80, 95, 100, 20);
        mSerialPortPanel.add(mBaudrateChoice);

        // 操作
        mOperatePanel.setBorder(BorderFactory.createTitledBorder("显示模式"));
        mOperatePanel.setBounds(230, 220, 290, 130);
        mOperatePanel.setLayout(null);
        add(mOperatePanel);

//		mDataInput.setBounds(25, 25, 265, 50);
//		mDataInput.setLineWrap(true);
//		mDataInput.setWrapStyleWord(true);
//		mOperatePanel.add(mDataInput);
        mSerialPortOperate.setFocusable(false);
        mSerialPortOperate.setBounds(20, 95, 90, 20);
        mOperatePanel.add(mSerialPortOperate);

        mDataASCIIChoice.setBounds(20, 25, 55, 20);
        mDataHexChoice.setBounds(95, 25, 55, 20);
        mDataIDSameChoice.setBounds(165, 25, 115, 20);
        mDataAliyunChoice.setBounds(20, 55, 115, 20);

//		mDataChoice.add(mDataASCIIChoice);
//		mDataChoice.add(mDataHexChoice);
        mOperatePanel.add(mDataASCIIChoice);
        mOperatePanel.add(mDataHexChoice);
        mOperatePanel.add(mDataIDSameChoice);
        mOperatePanel.add(mDataAliyunChoice);

//		mSendData.setFocusable(false);
//		mSendData.setBounds(180, 95, 90, 20);
//		mOperatePanel.add(mSendData);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mCommList = SerialPortManager.findPorts();
        // 检查是否有可用串口，有则加入选项中
        if (mCommList == null || mCommList.size() < 1) {
            ShowUtils.warningMessage("没有搜索到有效串口！");
        } else {
            for (String s : mCommList) {
                mCommChoice1.addItem(s);
                mCommChoice2.addItem(s);
            }
        }

//		mBaudrateChoice.addItem("9600");
//		mBaudrateChoice.addItem("19200");
//		mBaudrateChoice.addItem("38400");
//		mBaudrateChoice.addItem("57600");
        mBaudrateChoice.addItem("115200");
    }

//    /*
//    添加串口监听
//     */
//    private void addListener(SerialPort port, SerialPortEvent listener) throws TooManyListenersException {
//        //添加串口监听
//        port.addEventListener(new SerialPortEventListener() {
//            public void serialEvent(SerialPortEvent event) {
//                System.out.println("hello");//接收代码
//            }
//        });
//        port.notifyOnDataAvailable(true);//设置当有数据到达的时候唤醒监听接收线程
//        port.notifyOnBreakInterrupt(true);//设置当通信中断的时候唤醒中断线程
//
//    }
    /**
     * 按钮监听事件
     */
    private void actionListener() {
        // 串口
        mCommChoice1.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                mCommList = SerialPortManager.findPorts();
                // 检查是否有可用串口，有则加入选项中
                if (mCommList == null || mCommList.size() < 1) {
                    ShowUtils.warningMessage("没有搜索到有效串口！");
                } else {
                    int index = mCommChoice1.getSelectedIndex();
                    mCommChoice1.removeAllItems();
                    for (String s : mCommList) {
                        mCommChoice1.addItem(s);
                    }
                    mCommChoice1.setSelectedIndex(index);
                }
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // NO OP
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
                // NO OP
            }
        });
        mCommChoice2.addPopupMenuListener(new PopupMenuListener() {

            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                mCommList = SerialPortManager.findPorts();
                // 检查是否有可用串口，有则加入选项中
                if (mCommList == null || mCommList.size() < 1) {
                    ShowUtils.warningMessage("没有搜索到有效串口！");
                } else {
                    int index = mCommChoice2.getSelectedIndex();
                    mCommChoice2.removeAllItems();
                    for (String s : mCommList) {
                        mCommChoice2.addItem(s);
                    }
                    mCommChoice2.setSelectedIndex(index);
                }
            }

            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                // NO OP
            }

            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
                // NO OP
            }
        });

        // 打开|关闭串口
        mSerialPortOperate.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                String str = "打开串口";
                if (str.equals(mSerialPortOperate.getText()) && mSerialport == null) {
                    openSerialPort(e);//打开串口
//                    this.addListener(mSerialport, new SerialPortEvent());//监听串口数据
                } else {
//                    closeSerialPort(e);
                }
            }
        });

        // 发送数据
        mSendData.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //sendData(e);
            }
        });

        //打印字符串
        mButtonID.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                openSerialPortOffline(e);
                printID(mDataViewID_1.getText(), mDataViewID_2.getText(), mDataViewID_3.getText());
                SerialPortManager.closePort(mSerialport2);
            }
        });
        
        //查询设备列表
        mButtonDriver.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GetDriverList();
            }
        });
    }

    /*
     获取设备列表
     */
    void GetDriverList(){
        int iList = 0;
        int index = 1;      //显示的页数
        int iShowLine = 200;  //每页显示的行数(不超过200)
        List<String> lStringDevicerName;
        while (true) {            
            iList = Test.QueryDeviceTest(strProductKeyString,iShowLine,index++);
            if(iList>0){
                lStringDevicerName = Test.QueryDeviceName();
                for (int i = 0; i < lStringDevicerName.size(); i++) {
                    System.out.println(lStringDevicerName.get(i));
                    mDataView.append(lStringDevicerName.get(i)+"\r\n");
                }
            }else{
                break;
            }
        }
        
    }
    
    /**
     * 打开串口
     *
     * @param evt 点击事件
     */
    private void openSerialPortOffline(java.awt.event.ActionEvent evt) {
        // 获取串口名称
        String commName2 = (String) mCommChoice2.getSelectedItem();
        // 获取波特率，默认为9600
        int baudrate = 115200;
        String bps = (String) mBaudrateChoice.getSelectedItem();
        baudrate = Integer.parseInt(bps);
        // 检查串口名称是否获取正确
        if (commName2 == null || commName2.equals("")) {
            ShowUtils.warningMessage("没有搜索到有效串口！");
        } else {
            try {
                mSerialport2 = SerialPortManager.openPort(commName2, 9600);//打印机波特率
                if (mSerialport2 != null) {
                    //mDataView.setText("串口2已打开" + "\r\n");
                    mSerialPortOperate.setText("关闭串口");
                }
            } catch (PortInUseException e) {
                ShowUtils.warningMessage("串口2已被占用！");
            }
        }

    }

    /**
     * 打开串口
     *
     * @param evt 点击事件
     */
    private void openSerialPort(java.awt.event.ActionEvent evt) {
        // 获取串口名称
        String commName1 = (String) mCommChoice1.getSelectedItem();
        serialPortAliyunString = commName1;
        String commName2 = (String) mCommChoice2.getSelectedItem();
        // 获取波特率，默认为115200
        int baudrate = 115200;
        String bps = (String) mBaudrateChoice.getSelectedItem();
        baudrate = Integer.parseInt(bps);

        // 检查串口名称是否获取正确
        if (commName1 == null || commName1.equals("")) {
            ShowUtils.warningMessage("没有搜索到有效串口！");
        } else {
            try {
                mSerialport = SerialPortManager.openPort(commName1, baudrate);
//                mSerialport2 = SerialPortManager.openPort(commName2, 9600);//打印机波特率
                if (mSerialport != null) {
                    ID_ISOK = 0;
                    serialthread serialThread = new serialthread();//发送数据到上网卡
                    serialThread.start();
                    //mDataView.setText("串口1已打开" + "\r\n");
//                    mSerialPortOperate.setText("关闭串口");
                }
            } catch (PortInUseException e) {
                ShowUtils.warningMessage("串口1已被占用！");
            }
        }
        // 检查串口名称是否获取正确
        if (commName2 == null || commName2.equals("")) {
            ShowUtils.warningMessage("没有搜索到有效串口！");
        } else {
            try {
                mSerialport2 = SerialPortManager.openPort(commName2, 9600);//打印机波特率
                if (mSerialport2 != null) {
                    //mDataView.setText("串口2已打开" + "\r\n");
//                    mSerialPortOperate.setText("关闭串口");
                }
            } catch (PortInUseException e) {
                ShowUtils.warningMessage("串口2已被占用！");
            }
        }
//        // 添加串口监听
//        SerialPortManager.addListener(mSerialport, new SerialPortManager.DataAvailableListener() {
//
//            @Override
//            public void dataAvailable() {
//                try {
////                    mSerialport = iot.SerialPortManager.openPort(serialPortAliyunString, 115200);
//                    if (mSerialport != null) {
//                        ProcessSerialData(MainFrame.mSerialport);//处理串口数据
//                    }
//                } catch (PortInUseException ex) {
//                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            }
//        });
        // 添加串口监听
//        SerialPortManager.addListener(mSerialport, new SerialListenerMy());
    }

    /**
     * 关闭串口
     *
     * @param evt 点击事件
     */
    private void closeSerialPort(java.awt.event.ActionEvent evt) {
        ID_ISOK = 1;
        SerialPortManager.closePort(mSerialport);
        //mDataView.setText("串口已关闭" + "\r\n");
        mSerialPortOperate.setText("打开串口");
        mSerialport = null;

        SerialPortManager.closePort(mSerialport2);
        //mDataView.setText("串口已关闭2" + "\r\n");
        mSerialPortOperate.setText("打开串口");
        mSerialport2 = null;
    }

    /**
     * 发送数据
     *
     * @param evt 点击事件
     */
    public static void sendData() {
        // 待发送数据
        //String data = mDataInput.getText().toString();
        byte[] data = {(byte) 0xaa, (byte) 0x00, (byte) 0x03, (byte) 0x07, (byte) 0xf2, (byte) 0x30, (byte) 0xbb};
        //以十六进制的形式发送数据
        if (mSerialport != null) {
            SerialPortManager.sendToPort(mSerialport, data);
        }

    }

    /*
     输入：str1,第一个二维码；str2,第二个二维码；str3,第三个二维码
     输出：最后拼接成需要发送给打印机的二维码
     */
    private static String PrinterQrcode(String str1, String str2, String str3) {
        //拼接打印机字符串
        String strPinterTmp = "SIZE 96 mm,20 mm\r\nGAP 2 mm\r\nCLS\r\nSPEED 1.5\r\nDENSITY 15\r\n";
        strPinterTmp += "QRCODE 50,30,L,4,A,0,";
        strPinterTmp += str1;
        strPinterTmp += "\r\n";//字符串一拼接完成

        strPinterTmp += "QRCODE 420,30,L,4,A,0,";
        strPinterTmp += str2;
        strPinterTmp += "\r\n";//字符串二拼接完成

        strPinterTmp += "QRCODE 800,30,L,4,A,0,";
        strPinterTmp += (str3);
        strPinterTmp += "\r\n";//字符串三拼接完成
//        strPinterTmp += "\r\n"+"PRINT 1\r\n";
//        SerialPortManager.sendToPort(mSerialport2, strPinterTmp.getBytes());
        return strPinterTmp;
    }

    /*
     输入：str1,第一个字符串；str2,第二个字符串；str3,第三个字符串
     输出：最后拼接成需要发送给打印机的字符串
     */
    private static String PrinterStrs(String str1, String str2, String str3) {
        String[] strSplit1 = str1.split(",");
        String[] strSplit2 = str2.split(",");
        String[] strSplit3 = str3.split(",");
        String strPinterTmp1 = PrinterStr(strSplit1[0], strSplit1[1], strSplit1[2], "210");
        String strPinterTmp2 = PrinterStr(strSplit2[0], strSplit2[1], strSplit2[2], "580");
        String strPinterTmp3 = PrinterStr(strSplit3[0], strSplit3[1], strSplit3[2], "960");
//        SerialPortManager.sendToPort(mSerialport2, (strPinterTmp1+strPinterTmp2+strPinterTmp3+"PRINT 1\r\n").getBytes());
        return strPinterTmp1 + strPinterTmp2 + strPinterTmp3;
    }

    /*
     输入：str1,第一个字符串；str2,第二个字符串；str3,第三个字符串;strLocation 字符串排列的位置
     输出：最后拼接成需要发送给打印机的字符串
     */
    private static String PrinterStr(String str1, String str2, String str3, String strLocation) {
        String strPinterTmp = "TEXT " + strLocation + ",40,\"2\",0,1,1,";
        strPinterTmp += "\"" + str1 + "\"";
        strPinterTmp += "\r\n";//字符串一拼接完成

        strPinterTmp += "TEXT " + strLocation + ",90,\"1\",0,1,1,";
        strPinterTmp += "\"" + str2 + "\"";
        strPinterTmp += "\r\n";//字符串二拼接完成

        strPinterTmp += "TEXT " + strLocation + ",140,\"2\",0,1,1,";
        strPinterTmp += "\"" + str3 + "\"";
        strPinterTmp += ("\r\n");//字符串二拼接完成        

        return strPinterTmp;
    }

    /*
     文本框以字符的形式接收数据
     */
    private static void AsciiDisplay(String str) {
        if (mDataASCIIChoice.isSelected()) {
            mDataView.append(DateTime() + str + "\r\n");
        }
    }
    /*
     文本框以字符的形式接收数据
     */

    private static void AsciiDisplayByte(byte[] data) {
        if (mDataASCIIChoice.isSelected()) {
            mDataView.append(DateTime() + new String(data) + "\r\n");
        }
    }

    /*
     文本框以十六进制的形式接收数据
     */
    private static void HexDisplay(byte[] data) {
        if (mDataHexChoice.isSelected()) {
            mDataView.append(DateTime() + ByteUtils.byteArrayToHexString(data) + "\r\n");
        }
    }

    /*
     同一个ID不打印
     */
    private static void IdDisplay(String str) {
        if (str.length() > 0) {
            ID_ISOK = 1;
            mDataView.append("读取ID成功！\r\n");
//            SerialPortManager.closePort(mSerialport);
//            mSerialPortOperate.setText("打开串口");
            if (mDataIDSameChoice.isSelected()) {
                if (!strLast.equals(str)) {
                    strLast = str;
                    if (IdRegister(str)) {
                        Package(str);
                        Printer_3();
                    }
                } else {
                    mDataView.append(DateTime() + "同一个ID,请更换！\r\n");
                }
            } else {
                Package(str);
                Printer_3();
            }
        }
    }

    /*
     ID是否注册到阿里云
     */
    private static boolean IdRegister(String str) {
        if (mDataAliyunChoice.isSelected()) {
            String getDeviceNameString = Test.aliyun(strProductKeyString, str);
//            Test.rrpcTest("a13XVsM09B0", "868575022848636", "{\"Cmd\":1,\"Balance\":14.419000,\"DealID\":\"14542399161605\",\"WashPrice\":100,\"FrothPrice\":100,\"VacuumPrice\":100,\"WaterPrice\": 100}");
            if (getDeviceNameString.equals(str)) {
                mDataView.append(DateTime() + "阿里云注册成功！\r\n");
                return true;
            } else {
                mDataView.append(DateTime() + "阿里云注册失败！\r\n");
                mDataView.append(getDeviceNameString + "\r\n");
                return false;
            }
        } else {
            return true;
        }
    }

    /*
     打印字符串内的ID
     */
    private void printID(String str1, String str2, String str3) {
        IdDisplay(str1);
        IdDisplay(str2);
        IdDisplay(str3);
    }

    /*
     获取系统时间
     */
    private static String Date() {
        //获取时间
        Date now = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = ft.format(now);
        return strDate;
    }
    /*
     获取系统时间
     */

    private static String DateTime() {
        //获取时间
        Date now = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = ft.format(now);
        return strDate;
    }

    /*
     处理串口数据
     */
    public static void ProcessSerialData(byte[] data) throws PortInUseException {
//        byte[] data = SerialPortManager.readFromPort(mSerialport);//读取串口数据
        HexDisplay(data);
        AsciiDisplayByte(data);
        if (data.length > 0) {
            String byte_decode = decode.decodeSerial(data);//数据解码
            if (!byte_decode.equals("error")) {
//                AsciiDisplay(byte_decode);
//                HexDisplay(data);
                IdDisplay(byte_decode);
                System.out.printf("ID=%s\n", byte_decode);
//                IdRegister(byte_decode);
            } else {
                mDataView.append("数据解码错误\r\n");
            }

        } else {
//            MainFrame.mSerialport = SerialPortManager.openPort(serialPortAliyunString, 115200);
            mDataView.append("读取的数据长度为零\r\n");
        }
    }

    /*
     将数据打包成打印机识别的数据
     */
    private static String Package(String str) {
        String strShuangyinhao = "\\[\"]";
        String dataPrinterQRcode = "\"{" + strShuangyinhao + "productKey" + strShuangyinhao + ":" + strShuangyinhao
                + strProductKeyString + strShuangyinhao + "," + strShuangyinhao + "deviceName" + strShuangyinhao + ":" + strShuangyinhao
                + str + strShuangyinhao + "," + strShuangyinhao + "Date" + strShuangyinhao + ":" + strShuangyinhao + Date() + strShuangyinhao + "}\"";
        String dataPrinterString = strProductKeyString + "," + str + "," + Date();//,是分隔符
        vector.add(dataPrinterQRcode);
        vector.add(dataPrinterString);
        return str;
    }

    /*
     打印机按照3联排版打印
     */
    private static void Printer_3() {
        //判断是否存储满3个
        System.out.printf("打印标签的个数是：%s\n", vector.size() / 2);
        if (vector.size() == 6) {
            try {
                String dataSendtoPrinter = PrinterQrcode(vector.elementAt(0), vector.elementAt(2), vector.elementAt(4));
                String dataStrtmp = PrinterStrs(vector.elementAt(1), vector.elementAt(3), vector.elementAt(5));
                String dataStrtmp1 = dataSendtoPrinter + dataStrtmp + "PRINT 1\r\n";
                Thread.sleep(1000 * 1);
                SerialPortManager.sendToPort(mSerialport2, dataStrtmp1.getBytes());
                System.out.printf("打印标签的ID是：%s\n", vector.elementAt(1));
                System.out.printf("打印标签的ID是：%s\n", vector.elementAt(3));
                System.out.printf("打印标签的ID是：%s\n", vector.elementAt(5));
                vector.clear();
            } catch (InterruptedException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
}
